package com.zn.net
{
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.Endian;

	/**
	 * 协议
	 * @author 朱能
	 * 
	 */
	public class Protocol
	{
		//字符编码
		public static const CHARSET:String="GB2312";
		
		//key:int 	,	value:array:Function
		private static var _protocolDic:Dictionary=new Dictionary();
		
		/**
		 *注册协议 
		 * @param commandId
		 * @param callFunction
		 * 
		 */
		public static function registerProtocol(commandId:int, callFunction:Function) :void
		{
			if(!_protocolDic[commandId])
				_protocolDic[commandId]=new Vector.<Function>();
			
			_protocolDic[commandId].push(callFunction);
		}
		
		/**
		 *删除协议 
		 * @param commandId
		 * 
		 */
		public static function deleteProtocol(commandId:int):void
		{
			delete _protocolDic[commandId];
		}
		
		/**
		 * 注销协议中的方法
		 * @param commandId
		 * @param callFunction
		 * 
		 */
		public static function deleteProtocolFunction(commandId:int, callFunction:Function) :void
		{
			if(_protocolDic[commandId])
			{
				var v:Vector.<Function>=Vector.<Function>(_protocolDic[commandId]);
				
				var index:int=v.indexOf(callFunction);
				if(index!=-1)
					v.splice(index,1);
			}
		}
		
		/**
		 *根据协议获取注册的方法列表 
		 * @param commandId
		 * @return 
		 * 
		 */
		public static function getProtocolFunctionList(commandId:int):Vector.<Function>
		{
			if(_protocolDic[commandId])
				return Vector.<Function>(_protocolDic[commandId]);
			else 
				return new Vector.<Function>();
		}
		
		/**
		 *向流中添加字符串 
		 * @param str
		 * @param by
		 * 
		 */
		public static function writeByStr(str:String,by:ByteArray):void
		{
			var byStr:ByteArray=new ByteArray();
			byStr.endian=Endian.LITTLE_ENDIAN;
			byStr.writeMultiByte(str,CHARSET);
			byStr.position=0;
			
			by.writeShort(byStr.length);
			by.writeBytes(byStr);
		}
		
		/**
		 *从流中读取字符串 
		 * @param by
		 * @return 
		 * 
		 */
		public static function readByStr(by:ByteArray):String
		{
			var length:uint=by.readUnsignedShort();
			if(length==0)
				return "";
			return by.readMultiByte(length,CHARSET);
		}
	}
}